# coding=utf-8

from application import app, redis
from common.libs.JsonLibs import bytes_to_obj
from app.model.mysql.mall import Mall as MallMysql
from app.model.redis.mall import Mall as MallRedis
from app.json.mysql.mall import Mall as MallJson


def get_one(mall_id):
    redis_mall_one = redis.get(MallRedis.mall_one.key % mall_id)
    if redis_mall_one:
        mysql_mall_one = None
    else :
        mysql_mall_one = MallMysql.query.filter(MallMysql.id == mall_id, MallMysql.is_delete == 0).first()
    if mysql_mall_one:
        setInRedis(mysql_mall_one)
        mall_json = MallJson(mysql_mall_one).getJson()
    else :
        mall_json = bytes_to_obj(redis_mall_one)
    return mall_json


def get_list():
    redis_mall_set = redis.smembers(MallRedis.mall_set.key)
    redis_mall_list = list(redis_mall_set)
    redis_mall_list = redis_mall_list if redis_mall_list else []
    result_list = []
    if not redis_mall_list:
        mysql_mall_list = MallMysql.query.filter(MallMysql.is_delete == 0).order_by(MallMysql.g_id.asc(), MallMysql.g_num.asc()).all()
        for mysql_mall_one in mysql_mall_list:
            setInRedis(mysql_mall_one)
            mall_one_json = MallJson(mysql_mall_one).getJson()
            result_list.append(mall_one_json)
        return result_list
    else:
        for mall_id in redis_mall_list:
            mall_one_json = get_one(mall_id.decode("utf-8"))
            result_list.append(mall_one_json)
        return result_list


def setInRedis(mysql_mall_one):
    redis.sadd(MallRedis.mall_set.key, mysql_mall_one.id)
    redis.set(MallRedis.mall_one.key % mysql_mall_one.id, MallJson(mysql_mall_one).getJsonToRedis())
